<style>
.colorSeason .el-input__icon {
  line-height: 30px;
}
.colorSeason .color_top .el-input__inner {
  width: 160px;
  height: 30px;
}
.colorSeason .color_top .el-input {
  width: 160px;
  height: 30px;
  /* margin-top: 14px; */
}

.colorSeason .el-button {
  padding: 8px 15px;
  margin-right: 12px;
  height: 30px;
}
</style>

<style scoped>
.colorSeason {
  margin-right: 15px;
  padding: 0 15px;
  background-color: white;
  height: 95vh;
  position: relative;
}

.color_top {
  display: flex;
  padding-top: 14px;
  height: 60px;
  white-space: nowrap;
  border-bottom: 2px solid #f4f4f4;
}

.color_w {
  padding: 4px 6px 0 0;
  /* color: #757575; */
  /* font-weight: 1000; */
}
.l {
  margin-left: 16px;
}
.color_button {
  margin: 15px 0;
  display: flex;
  white-space: nowrap;
}

.footView span {
  float: left;
  margin-right: 48px;
  line-height: 6vh;
  font-size: 14px;
}
.footView span i {
  margin-right: 5px;
}
</style>

<template>
  <div class="colorSeason">
    <div class="color_top">
      <p class="color_w">色号</p>
      <el-input
        v-model="no"
        @keyup.enter.native="QueryNo"
        id="input"
      ></el-input>
      <p class="color_w l">颜色</p>
      <el-input v-model="name" clearable></el-input>
      <p class="color_w l">条码规律/品牌公司</p>
      <el-select
        v-model="brandedCompany"
        @keyup.enter.native="preservation()"
        style="margin-right: 20px"
        @change="query"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
      <el-button @click="query" icon="el-icon-search">查询</el-button>
      <el-button @click="dele1" icon="el-icon-delete"></el-button>
    </div>
    <!-- 按钮 -->
    <div class="color_button">
      <el-button
        @click="preservation"
        type="primary"
        style="z-index: 3"
        icon="el-icon-folder-checked"
        >保存</el-button
      >
      <!-- <div class="dr">
        <i class="el-icon-download"></i>
        导入
        <input ref="upload" accept=".xls, .xlsx" class="outputlist_upload" type="file" />
      </div> -->

      <el-button size="small" class="a-upload">
        <i class="el-icon-download"></i>导入
        <template>
          <input
            type="file"
            accept=".xlsx,.xls"
            @change="hanldeInsertClick"
            class="file"
          />
        </template>
      </el-button>

      <el-button @click="EXp" icon="el-icon-upload2">导出</el-button>
      <el-button @click="dele" icon="el-icon-delete" style="margin-left: 0"
        >删除</el-button
      >
    </div>
    <!-- 表格 -->
    <el-table
      :data="tableData"
      id="outTable"
      highlight-current-row
      style="width: 100%"
      height="74vh"
      @row-click="rowClick"
      :header-cell-style="{ background: '#f4f4f4', padding: 0, height: '40px' }"
      :cell-style="{ padding: 0, height: '36px' }"
    >
      <el-table-column prop="no" sortable label="色号" width="180">
      </el-table-column>
      <el-table-column prop="name" label="颜色" width="180"> </el-table-column>
      <el-table-column prop="brandedCompany" label="品牌公司">
        <!-- 图片 -->
      </el-table-column>
      <!-- <el-table-column>
      <template>
       <img src="./logo.png" width="100" height="100"/>
      </template>
      </el-table-column> -->
    </el-table>

    <foot-view
      class="footView"
      :pagesNum="pagesNum"
      :hasPagination="true"
      :pageSize="limit"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
    >
      <div slot="text">
        <span>数据库：{{ jxQuarter }}</span>
      </div>
    </foot-view>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
import {
  getColorSeason,
  getBranded,
  postColorSeason,
  postColorInsertList,
  deleteColorSeason,
  putColorSeason,
  deleteColorSeason1,
  getColorSeason2,
  postExcelColor
} from '../../../network/colorSeason'
import enterUp from '../../../components/mixins/enterUp'
import footView from '../../../components/FootView'
import outex from '../../../components/mixins/outexp'

export default {
  name: 'colorSeason',
  mixins: [enterUp, outex],
  created() {
    let jxQuarterVal = document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))
    this.jxQuarter = jxQuarterVal ? jxQuarterVal[1] : null

    this.inpList = this.getInput()
    // 总条数，页码赋值
    getColorSeason().then((res) => {
      this.dataLen = res.data.total
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    })
    this.query()

    // this._getColorSeason({limit: this.limit,page: this.currentPage})
    this._getBranded()
  },
  data() {
    return {
      inpList: [],
      tableData: [],
      JList: [],
      outputs: [],
      csj: [],
      JKL: [],
      bkl: [],
      options: [{ label: '全部', value: '' }],
      no: '',
      name: '',
      brandedCompany: '',
      id: '',
      // 总数据条数
      dataLen: 0,
      // 总页码
      pagesNum: 0,
      // 分页条数
      limit: 20,
      // 当前页码
      currentPage: 1,
      jxQuarter: null
      // jxQuarter: document.cookie.match(RegExp('jxQuarter' + '=([^;]+)'))[1]
    }
  },
  watch: {
    dataLen(a, b) {
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
    }
  },
  components: {
    footView
  },
  methods: {
    EXp() {
      getColorSeason().then((res) => {
        console.log(res.data)
        this.tableData = res.data.data
        this.$nextTick(() => {
          this.exp()
          this._getColorSeason({ limit: this.limit, page: this.currentPage })
        })
      })
    },

    //按品牌公司查询
    //輸入編號 如果已存在 回車自動出現 編號信息
    //光标到第三个后自动触发保存 之后 光标跳到第一个 保存成功 数据 查到第一条位置显示
    query() {
      let obj = {
        no: this.no,
        name: this.name,
        brandedCompany: this.brandedCompany,
        limit: this.limit,
        page: this.currentPage
      }
      getColorSeason(obj).then((res) => {
        console.log(res.data)
        if (res.data.code == 200) {
          this.tableData = res.data.data

          var sor = this.tableData.slice(-1)
          console.log(sor, 'sor')
          if (!sor.length) return
          var sortList = JSON.parse(JSON.stringify(sor).replace(/\[|]/g, ''))
          console.log(sortList)
          this.tableData.pop()
          this.tableData.unshift(sortList) //让新添加的数据在最上面显示

          this.tableData.sort((a, b) => {
            //brandedCompany相同的在一起显示
            if (a['brandedCompany'] != b['brandedCompany']) {
              return a['brandedCompany'].localeCompare(b['brandedCompany'])
            }
          })
        }
      })
    },
    //按品牌公司删除
    dele1() {
      let obj = { brandedCompany: this.brandedCompany }
      // console.log(this.brandedCompany)
      this.$confirm('是否删除此品牌公司所有颜色建档的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteColorSeason1(obj).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.query() //删除后更新查询
            }
          })
          this.$message({
            type: 'success',
            offset: 400,
            message: '删除成功!'
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            offset: 400,
            message: '已取消删除'
          })
        })
    },

    dele() {
      if (this.id == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '请选择要删除的数据'
        })
        return
      }
      let obj = { id: this.id }
      this.$confirm('是否删除此色号的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          deleteColorSeason(obj).then((res) => {
            console.log(res.data)
            if (res.data.code == 200) {
              this.dataLen--
              this._getColorSeason(
                this._getColorSeason({
                  limit: this.limit,
                  page: this.currentPage
                })
              )
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            } else if (res.data.code == 204) {
              this.$message.error({
                message: '该数据有关联数据,删除失败'
              })
            } else {
              this.$message.error({
                message: '删除失败'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            offset: 400,
            message: '已取消删除'
          })
        })
    },

    _getColorSeason(params = { limit: 99999 }) {
      getColorSeason(params).then((res) => {
        console.log(res)
        this.tableData = res.data.data
        this.name = ''
        this.brandedCompany = ''
        this.no = ''
        this.id = ''
        if (this.tableData.length == 0 && this.currentPage > 1) {
          this.currentPage--
          this._getArtNo({ limit: this.limit, page: this.currentPage })
        }
      })
    },
    _getBranded() {
      getBranded({ limit: 99999 }).then((res) => {
        console.log(res.data)
        //获取的数据循环到下拉菜单里
        let list = res.data.data
        list.forEach((element) => {
          this.options.push({ label: element.company, value: element.company })
        })
        // console.log(this.options)
      })
    },
    //保存
    preservation() {
      this.InpFocus()
      if (this.no == '' || this.name == '' || this.brandedCompany == '') {
        this.$message({
          type: 'warning',
          offset: 400,
          message: '色号，颜色和品牌公司不能为空'
        })
        return
      }
      var obj = {
        name: this.name,
        brandedCompany: this.brandedCompany,
        no: this.no,
        id: this.id
      }
      var obj1 = {
        name: this.name,
        brandedCompany: this.brandedCompany,
        no: this.no
      }
      for (const i of this.tableData) {
        if (i.no == this.no) {
          this.$confirm('此操作将修改此色号的数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              putColorSeason(obj).then((res) => {
                this._getColorSeason()
                if (res.data.code == 200) {
                  this.$message({
                    type: 'success',
                    offset: 400,
                    message: '修改成功!'
                  })
                } else {
                  this.$message.error({
                    offset: 400,
                    message: '修改失败'
                  })
                }
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                offset: 400,
                message: '已取消修改'
              })
            })
          return
        }
      }
      // console.log
      postColorSeason(obj1).then((res) => {
        console.log(res)
        if (res.data.code == 200) {
          this.dataLen++
          this.InpFocus()

          // this._getColorSeason()
          // this._getColorSeason({limit: this.limit,page: this.currentPage})
          this.no = ''
          this.name = ''
          this.query()
        } else if (res.data.code !== 200) {
          this.$message.error({
            offset: 400,
            message: '添加失败'
          })
        }
      })
    },
    InpFocus() {
      var pFocus = document.getElementById('input')
      pFocus.focus()
      pFocus.select()
    },
    rowClick(e) {
      //console.log(e)
      this.no = e.no
      this.name = e.name
      this.brandedCompany = e.brandedCompany
      this.id = e.id
    },
    // 每页显示页数改变
    handleSizeChange(val) {
      this.limit = val
      // 总页码赋值
      this.pagesNum = Math.ceil(this.dataLen / this.limit)
      this._getColorSeason({ limit: this.limit, page: this.currentPage })
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this._getColorSeason({ limit: this.limit, page: this.currentPage })
    },

    // readExcel(e) {
    //   // console.log(111)
    //   //表格导入
    //   if(this.brandedCompany == ''){
    //     this.$alert('请选择条码规律/品牌公司', '提示', {
    //       confirmButtonText: '确定',
    //     });
    //     return
    //   }
    //   var that = this;
    //   const files = e.target.files;
    //   console.log(files);
    //   if (files.length <= 0) {
    //     //如果没有文件名
    //     return false;
    //   } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
    //     this.$Message.error("上传格式不正确，请上传xls或者xlsx格式");
    //     return false;
    //   }

    //   const fileReader = new FileReader();
    //   fileReader.onload = ev => {
    //     try {
    //       const data = ev.target.result;
    //       const workbook = XLSX.read(data, {
    //         type: "binary"
    //       });
    //       const wsname = workbook.SheetNames[0]; //取第一张表
    //       const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
    //       console.log(ws);
    //       for(var a=0;a<ws.length;a++){
    //           this.JList.push(JSON.stringify(ws[a]));
    //         }
    //         console.log(this.JList)
    //       // let obj = {paramsList:ac,fieldMap:{brandedCompany:"123456"}}
    //       let obj = {paramsList:this.JList,fieldMap:{brandedCompany:this.brandedCompany}}
    //       console.log({obj})
    //       postExcelColor(obj).then(res=>{
    //         console.log(res.data)
    //         if(res.data.code == 200){
    //           this.$message({
    //             type: 'success',
    //             message: '导入成功!'
    //           });
    //           this._getColorSeason({limit: this.limit,page: this.currentPage})//重新请求页面数据
    //         }else{
    //           this.$message({
    //             type: 'info',
    //             message: '导入失败，色号不可重复!'
    //           });
    //         }
    //       })

    //       that.outputs = []; //清空接收数据
    //       //编辑数据
    //       for (var i = 0; i < ws.length; i++) {
    //         var sheetData = {
    //           address: ws[i].addr,
    //           value: ws[i].value
    //         };
    //         that.outputs.push(sheetData);

    //       }
    //       this.$refs.upload.value = "";
    //     } catch (e) {
    //       return false;
    //     }
    //   };
    //   fileReader.readAsBinaryString(files[0]);

    // },

    QueryNo() {
      if (this.no != '') {
        for (let w of this.tableData) {
          if (this.no == w.no) {
            this.tableData = [w]
          }
        }
      }
    },

    /**
     * 新建
     */
    // 批量 导入
    hanldeInsertClick(evt) {
      const { files } = evt.target
      let fileReader = new FileReader()
      fileReader.onload = async (event) => {
        try {
          const { result } = event.target
          // 以二进制流方式读取得到整份excel表格对象
          const workbook = XLSX.read(result, { type: 'binary' })
          let tableList = [] // 存储获取到的数据
          // 遍历每张工作表进行读取（这里默认只读取第一张表）
          for (const sheet in workbook.Sheets) {
            if (workbook.Sheets.hasOwnProperty(sheet)) {
              // 利用 sheet_to_json 方法将 excel 转成 json 数据
              tableList = tableList.concat(
                XLSX.utils.sheet_to_json(workbook.Sheets[sheet])
              )
              // break; // 如果只取第一张表，就取消注释这行
            }
          }
          /**
           * 1,获取导入表格的数据
           * 2,判断 head 是否正确
           * 3，根据 head 修改对应的请求参数
           */
          if (!tableList.length) return this.$message.error('导入的数据为空')
          const tableItem = tableList[0]
          const element = Object.keys(tableItem)
          const titleStr = '色号,颜色,品牌公司'
          if (element.toString() !== titleStr)
            return this.$message.error('导入的表格头部不正确,请检查后再导入')

          console.log(tableList)

          // return
          let newDataList = tableList.map((item, index) => {
            return {
              no: item['色号'],
              name: item['颜色'],
              brandedCompany: item['品牌公司']
            }
          })
          console.log(newDataList)

          // return
          // 发送请求
          const { data } = await postColorInsertList(newDataList)
          if (data && data.code === 200) {
            this.$message.success(data.msg)
            this._getColorSeason()
          }
        } catch (e) {
          this.$message.error(e)
        }
      }

      // 以二进制方式打开文件
      fileReader.readAsBinaryString(files[0])
    }
    // toggleSelection(rows) {
    //   if (rows) {
    //     rows.forEach(row => {
    //       this.$refs.multipleTable.toggleRowSelection(row);
    //     });
    //   } else {
    //     this.$refs.multipleTable.clearSelection();
    //   }
    // },
    // handleSelectionChange(val) {
    //   this.multipleSelection = val;
    // },
  }
  // mounted() {
  //   this.$refs.upload.addEventListener("change", e => {
  //     //绑定监听表格导入事件
  //     this.readExcel(e);
  //   });
  // },
}
</script>
